import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Tabs, Menu, Spin, Icon, message, Radio, Row, Col, Button, Badge, Popconfirm } from 'antd'
const TabPane = Tabs.TabPane;
const RadioGroup = Radio.Group;
import configureStore from "stores";
import SubsidySettingComp from "containers/expense-reimbursement-control/subsidy-rule/subsidy-rule-setting-list";
import { setDefaultSetOfBook } from "actions/cache";
import AdvancedTable from 'components/advanced-table'
const SimpleTable = AdvancedTable.SimpleTable;
import SlideFrame from 'components/slide-frame'
import errorMessage from "share/errorMessage";
import Priority from 'components/template/priority'
import NewSubsidyRuleConfig from 'containers/application-setting/new-fp-setting'
import SubsidyRuleConfigDefault from 'containers/application-setting/default-fp-setting'
import subsidyRuleService from 'containers/expense-reimbursement-control/subsidy-rule/subsidy-rule-service'
import subsidySettingData from 'containers/expense-reimbursement-control/subsidy-rule/subsidy-setting-data'
import Info from 'components/info'
import "styles/setting/workflow-config/workflow-config.scss"
const options = [
  { label: messages('common.all')/*全部*/, value: 'ALL' },
  { label: messages('expense-8.key231')/*租户*/, value: 'TENANT' },
  { label: messages('expense-8.key2')/*公司*/, value: 'COMPANY' },
];
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15, offset: 1 },
};
class SubsidyRuleStandard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      nowKey: 'subsidy-setting',
      loading: true,
      nowTab: 'travelStandard',
      setOfBooks: [],
      nowSetOfBooks: {
        id: '',
        setOfBooksName: '',
        nowTab: ''
      },
      tableConfig: {
        columns: [{
          dataIndex: 'levelCode', title: messages('expense-8.key1')/*层级*/,
          render: (text) => {
            return <span>
              {text === 'COMPANY' ? messages('expense-8.key2')/*公司*/ : messages('expense-8.key231')/*租户*/}</span>
          }
        }, {
          dataIndex: 'levelOrgName', title: messages('expense-8.key8')/*所属组织*/,
          render: (text,record) =>  text
        }, {
          dataIndex: 'enabled', title: messages('common.column.status')/*状态*/,
          render: (text) => {
            return <span>
            <Badge status={text ? "success" : 'error'}/>
              {text ? messages('common.status.enable')/*启用*/ : messages('expense-8.key84')/*禁用temp*/}</span>
          }
        }, {
          title: messages('common.operation')/*操作*/,
          dataIndex: 'delete',
          render: (value, record) =>
          !record.readOnly && <Popconfirm
            placement="bottomRight"
            title={messages('expense-8.key344')/*您确定删除这条规则吗？*/}
            onConfirm={e => this.handleDelete(e, record)}
          >
            <a
              onClick={e => {
                e.preventDefault();
                e.stopPropagation()
              }}>
              {messages('common.delete')/*删除*/}
            </a>
          </Popconfirm>
        },],
        searchForm: [
          {
            id: 'levelCode',
            initialValue: 'ALL',
            label: messages('expense-8.key1')/*层级*/,
            component: <RadioGroup options={options} initialValue="ALL"/>,
            tagParser: value => this.getLevelTypeValue(value),
            dataIndex: 'levelCode',
          }, {
            id: 'companyIds',
            dataIndex: 'levelOrgName',
            label: messages('expense-8.key8')/*所属组织*/,
            parser: value => ({ companyIds: value ? value.rangeValue.id : null }),
            tagParser: value => value && value.rangeValue.name,
            component: <Priority
              style={{ marginLeft: 0 }}
              formItemLayout={formItemLayout}
              top='TENANT'
              onlyCompany
              showCompanyComponent={false}
              showCompany
              companyProps={{
                single: true
              }}
            />,
          }
        ],
      }
    }
  }

  getLevelTypeValue(type) {
    let text = messages('common.all')/*全部*/;
    switch(type) {
      case 'TENANT':
        text = messages('expense-8.key231')/*租户*/;
        break;
      case 'COMPANY':
        text = messages('expense-8.key2')/*公司*/;
        break;
    }
    return text;
  }

  callback = e => {
    let { nowKey } = this.state;
    this.setState({ nowKey: e })
  };

  afterCloseSlideFrame = flag => {
    if (flag) {
      this.advancedTableRef.getList();
    }
  };

  handleDelete = (e, record) => {
    e.stopPropagation();
    subsidyRuleService.deleteSubsidyConfig({ id: record.id })
      .then(res => {
        this.advancedTableRef.getList();
      }).catch(e => {
      errorMessage(e.response)
    })
  };

  service = (page, size, searchParams, extraParams) => {
    if (searchParams.levelCode === 'ALL') {
      searchParams.levelCode = ''
    }
    return subsidyRuleService.getSubsidyConfigList({ page, size, ...searchParams })
  };

  handleCreate = (title, nowMode, id = null) => {
    const { nowKey } = this.state;
    let pageFile = NewSubsidyRuleConfig, apiService = '', saveApiService = '';
    //配置接口
    switch(nowMode) {
      case 'create':
        pageFile = NewSubsidyRuleConfig;
        apiService = subsidyRuleService.getSubsidyDefaultConfig;
        saveApiService = subsidyRuleService.postSubsidyConfig;
        break;
      case 'default':
        pageFile = SubsidyRuleConfigDefault;
        apiService = subsidyRuleService.getSubsidyDefaultConfig;
        break;
      case 'edit':
        pageFile = NewSubsidyRuleConfig;
        apiService = subsidyRuleService.getSubsidyConfigDetail;
        saveApiService = subsidyRuleService.putSubsidyConfigDetail;
        break;
    }
    SlideFrame.open({
      title: title,
      content: pageFile,
      afterClose: this.afterCloseSlideFrame,
      params: {
        id,
        apiService,
        formItemLayout: {
          labelCol: { span: 4 },
          wrapperCol: { span: 16 },
        },
        saveApiService,
        configFp: subsidySettingData['subsidy-setting'].configs,
      }
    }, this)
  };

  render() {
    const { setOfBooks, tableConfig, nowKey } = this.state;
    const { currentMenuPermission } = this.props;
    let { permissionLoading } = currentMenuPermission;
    const infoData = (nowKey === 'subsidy-setting') && {
      dataSource: { explain: subsidySettingData[nowKey].description },
      attributes: [{ title: messages('expense-8.key6')/*说明*/, dataIndex: 'explain', span: 24 }]
    };
    const attributes = infoData && infoData.attributes && infoData.attributes.map(i => {i.widthFix = false; return i;});
    return (
      <div className='subsidy-rules' style={{marginTop: '-16px', marginBottom: '-16px'}}>
        <Spin spinning={permissionLoading}>
          <Tabs defaultActiveKey="subsidy-setting" onChange={this.callback}>
            <TabPane tab={messages('expense-8.key343')/*差补设置*/} key="subsidy-setting">
            </TabPane>
            <TabPane tab={messages('expense-8.key212')/*差补规则设置*/} key="subsidy-rule-setting">
            </TabPane>
          </Tabs>
          { nowKey === 'subsidy-setting' &&
          <div className="subsidy-setting full-height-page" style={{height: 'calc(100vh - 116px)'}}>
            <SimpleTable
              onRef={ref => this.advancedTableRef = ref}
              style={{ marginTop: 10 }}
              {...tableConfig}
              onRow={record => ({
                onClick: () => this.handleCreate('编辑', 'edit', record.id)
              })}
              rowKey="id"
              onGetDataError={e => errorMessage(e.response)}
              service={this.service}
            >
              {infoData && <Info paragraph
                              dataSource={infoData.dataSource}
                              attributes={attributes}/>
              }
              <Row type="flex" className="handle-row" justify="space-between" align="middle">
                <Col span={12}>
                  <Button
                    type="primary"
                    onClick={() => this.handleCreate(messages('common.create')/*新建*/, 'create')}>
                    {messages('common.create')/*新建*/}
                  </Button>
                </Col>
                <Col span={12} className={'default-btn'}>
                  <div className="default-btn-text"
                       onClick={() => this.handleCreate(messages('expense-8.key236')/*默认规则*/, 'default')}>
                    <Icon type="file-text"
                          style={{ marginRight: 5 }}/>{messages('expense-8.key236')/*默认规则*/}
                  </div>
                </Col>
              </Row>
            </SimpleTable>
          </div>
          }
          {!permissionLoading && nowKey === 'subsidy-rule-setting' &&
          <SubsidySettingComp
            currentMenuPermission={currentMenuPermission.currentMenuPermission}
          />}
        </Spin>
      </div>
    )
  }
}

SubsidyRuleStandard.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode,
    currentMenuPermission: state.main.currentMenuPermission,
  }
}

export default connect(mapStateToProps)(SubsidyRuleStandard)
